//
//  GetMoneyOrganizationVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/7/10.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "GetMoneyOrganizationVC.h"
#import "GetMoneyOrganizationCell.h"
#import "FirstAuditingModel.h"
#import "FirstAuditingDetailListVC.h"
#import "FirstAuditingSearchView.h"

@interface GetMoneyOrganizationVC ()<TCAlertViewDelegate>
/**
 当前页码
 */
@property (nonatomic, assign) NSInteger CurrentPage;
/**
 临时页码
 */
@property (nonatomic, assign) NSInteger TempPage;
/**
 数据存放
 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/**
 默认是-1，代表搜索全部
 */
@property (nonatomic, assign) NSInteger OrganizationId;


@property (nonatomic, strong) TCAlertView *alertView;

@property (nonatomic,copy)NSString *textStr;
@property (nonatomic,assign) NSInteger index;


@end

@implementation GetMoneyOrganizationVC


- (void)viewDidLoad
{
    [super viewDidLoad];

    // 配置TableView
    [self SetupTableView];

}



#pragma mark  - 配置
/**
 配置TableView
 */
- (void)SetupTableView
{
    // 占位
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    // 预注册
    [self.tableView registerNib:[UINib nibWithNibName:[GetMoneyOrganizationCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    // 预估高度
    self.tableView.rowHeight = 180;
    //默认页码
    self.CurrentPage = 1;
    //默认ID
    self.OrganizationId = -1;
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        //取当前页码给临时页码
        self.TempPage = self.CurrentPage;
        //设当前页码为1
        self.CurrentPage = 1;
        //请求
        [self RefreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        //请求
        [self RefreshData];
    }];
    //开始刷新
    [self.tableView.mj_header beginRefreshing];
}


/**
 刷新失败时，判断是否需要从临时页码里取出来给当前页码
 */
- (void)GetPage
{
    if (self.CurrentPage == 1)
    {
        self.CurrentPage = self.TempPage;
    }
}

/**
 结束刷新

 @param Index 0:结束刷新 1:提示没有更多数据 2:tableView数据源更新
 */
- (void)EndRefresh:(NSInteger)Index;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (Index)
        {
            case 0:
            {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
                break;
            case 1:
            {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
                break;
            case 2:
            {
                [self.tableView reloadData];
            }
                break;
            default:
                break;
        }
    });
}



#pragma mark - 网络请求
/**
 网络请求
 */
- (void)RefreshData
{

    NSDictionary *Params = @{
                             @"action"          :[self GetAction],
                             @"organizationId"  :@(self.OrganizationId),
                             @"pageNumber"      :@(self.CurrentPage)
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        //结束刷新
        [self EndRefresh:0];
        //判断是否加载成功
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {

            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 判断是否为空，为空的话显示没有数据了
            if (Arr.count == 0)
            {
                [self EndRefresh:1];
            }
            else
            {
                // 清空数据
                if (self.CurrentPage == 1)
                {
                    [self.DataArr removeAllObjects];
                }
                // 转对象
                [Arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    FirstAuditingModel *Model = [FirstAuditingModel HNObjectValuesForKey:(NSDictionary *)obj];
                    [self.DataArr addObject:Model];
                }];


                //数据请求成功，页码加1
                self.CurrentPage += 1;
                // 通知刷新
                [self EndRefresh:2];
            }
        }
        else
        {
            //页码处理
            [self GetPage];
            //显示错误信息
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {

        //结束刷新
        [self EndRefresh:0];
        //页码处理
        [self GetPage];
        //显示错误信息
        [MBProgressHUD showError:NetErr];
    }];
}


/**
 根据枚举返回Action
 */
- (NSString *)GetAction
{
    // 资金提现
    if (self.GetMoneyOrganizationType == GetMoneyOrganizationMoney)
    {
        return @"waitWithdraw";
    }
    // 星币提现
    else if (self.GetMoneyOrganizationType == GetMoneyOrganizationCoins)
    {
        return @"waitWithdrawCoins";
    }else if (self.GetMoneyOrganizationType == GetMoneyOrganizationCoinsTaocan){
        
        return @"waitWithdrawPackage";
    }

    else
    {
        return @"未知";
    }
}


#pragma mark - TableView代理
//区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

//Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取出对象
    FirstAuditingModel *Model = self.DataArr[indexPath.row];
    // 实例Cell
    GetMoneyOrganizationCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    // 点语法
    Cell.Model = Model;
    // 点击按钮事件
    Cell.ClickButton = ^(UIButton *Button)
    {
        // 处理点击事件
        [self MgrCellClick:Button Model:Model];
    };
    return Cell;
}



// 头部视图的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

// 头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [FirstAuditingSearchView ConfigSearchViewWithSearchResult:^(NSString *Str) {
        // 开始搜索啦
        // 页码为1
        self.CurrentPage = 1;
        // 清空数据源
        [self.DataArr removeAllObjects];
        // 动画刷新下界面
        [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:0] withRowAnimation:(UITableViewRowAnimationAutomatic)];
        // 得到机构ID
        self.OrganizationId = [Str integerValue];
        // 开始刷新
        [self.tableView.mj_header beginRefreshing];
    }];
}
#pragma mark - 处理点击事件
/**
 Button.tag:1100通过 1101拒绝 1102查看详情
 */
- (void)MgrCellClick:(UIButton *)Button Model:(FirstAuditingModel *)Model
{

    NSInteger tag = Button.tag;
    // 1、找出该Model在数据源的位置
    NSInteger Index = [self.DataArr indexOfObject:Model];
    // 2、从数据源中移除对象
    [self.DataArr removeObject:Model];
    if (1100 == tag) {


        [self netWorkwithdrawId:[NSString stringWithFormat:@"%@",Model.withdrawId]  indexPath:Index];



    }else if (1101 == tag){


        [self netWorkwithdrawIdTow:[NSString stringWithFormat:@"%@",Model.withdrawId] indexPath:Index];


        

    }
    else if (Button.tag == 1102)
    {
        // 实例详情
        FirstAuditingDetailListVC *VC = [[FirstAuditingDetailListVC alloc] init];
        // 传值
        VC.withdrawNo = Model.withdrawNo;
        // 身份
        VC.FirstAuditingDetailListType = self.GetMoneyOrganizationType == GetMoneyOrganizationMoney?FirstAuditingDetailListMoney:FirstAuditingDetailListCoins;
        // 跳转
        [self.navigationController pushViewController:VC animated:YES];
    }


}


#pragma mark ---- 通过方法的实现
- (void)netWorkwithdrawId:(NSString *)withdrawId indexPath:(NSInteger)index{




    ZYalertController *arert = [ZYalertController alertControllerWithTitle:@"温馨提示" message:@"你是否允许通过" preferredStyle:UIAlertControllerStyleAlert];

    ZYAlertAction  *action = [ZYAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

        
        NSDictionary *Params;
        
        
        if (self.GetMoneyOrganizationType == GetMoneyOrganizationMoney) {
           Params = @{
                                     @"action" :@"review",
                                     @"withdrawFlag" :@"2",
                                     @"withdrawId":withdrawId,
                                     };

            
        }else if (self.GetMoneyOrganizationType == GetMoneyOrganizationCoins){
            
            Params = @{
                                     @"action" :@"reviewCoins",
                                     @"withdrawFlag" :@"2",
                                     @"withdrawId":withdrawId,
                                     };
            

        }else if (self.GetMoneyOrganizationType == GetMoneyOrganizationCoinsTaocan){
            
            Params = @{
                                     @"action" :@"reviewPackage",
                                     @"withdrawFlag" :@"2",
                                     @"withdrawId":withdrawId,
                                     };

            
        }

        
        





        [NetManager Post:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

            if ([Obj[@"code"] isEqualToNumber:@1000]){
                // 3、表单删除Cell
                [self.tableView beginUpdates];
                [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:(UITableViewRowAnimationAutomatic)];
                [self.tableView endUpdates];
            }else{
                [MBProgressHUD showError:Obj[@"msg"]];

            }



        } Fail:^(NSError *Error) {

        }];



    }];


    ZYAlertAction *actionTow = [ZYAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {


    }];
    action.textColor = [UIColor blackColor];
    actionTow.textColor = [UIColor blackColor];
    [arert addAction:action];
    [arert addAction:actionTow];
    [self presentViewController:arert animated:YES completion:nil];













}





#pragma mark ---- 拒绝方法的实现
- (void)netWorkwithdrawIdTow:(NSString *)withdrawId indexPath:(NSInteger)index{

    [self.alertView showView];

    self.textStr = withdrawId;
    self.index = index;


}


#pragma mark ---- TCAlertViewDelegate
- (void)requestEventAction:(UIButton *)button{

    [self.alertView closeView];
    NSDictionary *Params;
    
    if (self.GetMoneyOrganizationType == GetMoneyOrganizationMoney) {
        Params = @{
                                 @"action":@"review",
                                 @"withdrawFlag" :@"1",
                                 @"withdrawId":self.textStr,
                                 @"reason":self.alertView.remarkField.text,
                                 };

    }else if (self.GetMoneyOrganizationType == GetMoneyOrganizationCoins){
        Params = @{
                                 @"action":@"reviewCoins",
                                 @"withdrawFlag" :@"1",
                                 @"withdrawId":self.textStr,
                                 @"reason":self.alertView.remarkField.text,
                                 };

        
    }else if (self.GetMoneyOrganizationType == GetMoneyOrganizationCoinsTaocan){
        
        Params = @{
                                 @"action":@"reviewPackage",
                                 @"withdrawFlag" :@"1",
                                 @"withdrawId":self.textStr,
                                 @"reason":self.alertView.remarkField.text,
                                 };

    }
    






    NSLog(@"%@ %@",LLBaseURL(@"yxhUser.do"),[AccountTool shareAccountTool].currentAccount.authCode );

    [NetManager Post:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        if ([Obj[@"code"] isEqualToNumber:@1000]){

            // 3、表单删除Cell
            [self.tableView beginUpdates];
            [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.index inSection:0]] withRowAnimation:(UITableViewRowAnimationAutomatic)];
            [self.tableView endUpdates];
        }





    } Fail:^(NSError *Error) {

    }];



}


- (TCAlertView *)alertView {
    if (!_alertView) {
        self.alertView = [[TCAlertView alloc] initWithFrame:CGRectMake(30, 200, [UIScreen mainScreen].bounds.size.width - 60, 220)];
        self.alertView.backgroundColor = [UIColor whiteColor];
        self.alertView.delegate = self;
    }
    return _alertView;
}

#pragma mark - Setter
- (NSMutableArray *)DataArr{
    if (!_DataArr)
    {
        self.DataArr = [NSMutableArray array];
    }
    return _DataArr;
}



@end
